package com.vietnam.power.service.impl;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.vietnam.power.constant.ProductConstant;
import com.vietnam.power.dao.LocationDao;
import com.vietnam.power.dao.ProductDao;
import com.vietnam.power.domain.CategoryDTO;
import com.vietnam.power.domain.ProductDTO;
import com.vietnam.power.persistence.Category;
import com.vietnam.power.persistence.Location;
import com.vietnam.power.persistence.Product;
import com.vietnam.power.service.ProductService;

@Service
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
public class ProductServiceImpl implements ProductService {
	@Autowired
	private ProductDao productDao;
	@Autowired
	private LocationDao locationDao;

	public List<CategoryDTO> getAllCategories() {
		List<CategoryDTO> activeCategories = new ArrayList<CategoryDTO>();

		for (Category cate : productDao.getAllParentCategories()) {
			CategoryDTO dto = new CategoryDTO(cate.getCategoryId(), cate.getCategoryName(), cate.getFile().getThumbPath(), true);
			activeCategories.add(dto);
			// get child cate
			for (Category childCate : productDao.getAllChildrenCategories(cate.getCategoryId())) {
				dto = new CategoryDTO(childCate.getCategoryId(), childCate.getCategoryName(), childCate.getFile().getThumbPath(), false);
				activeCategories.add(dto);
			}
		}

		return activeCategories;
	}
	
	public ProductDTO getProductById(Long id) {
		Product product= productDao.getProductById(id);
		NumberFormat formatter = new DecimalFormat(ProductConstant.CURRENCY_FORMART);
		String formattedNumber = formatter.format(product.getUnitPrice());
		ProductDTO dto= new ProductDTO(product.getProductId(), product.getCreatedDate(), product.getDeleted(), product.getDescription(),product.getDescription(), product.getSold(), formattedNumber, product.getLocation().getLocationName(), product.getCategory());
		return dto;
	}
}
